package projects

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/beego/beego/v2/server/web/pagination"
	"log"
	"strconv"
	"strings"
	"xpms/controllers"
	"xpms/cores"
	"xpms/cores/utils"
)

// 计划管理
type PlanProjectController struct {
	controllers.BaseController
}

// @Title 分页查询项目计划数据
// @Description 分页查询项目计划数据
// @Param	id		path 	string	true		"项目id"
// @Param	p		query 	int	true		"第几页"
// @Param	pageoffset		query 	int			"每页数"
// @Param	createStarted		query 	int64			"创建开始时间"
// @Param	createEnd		query 	int64			"创建结束时间"
// @Param	keywords		query 	string			"关键字"
// @Success 200 {object} projects.ProjectsPlanDto   int   int  int
// @Failure 403 module not exist
// @router /:id/page [get]
func (u *PlanProjectController) Page() {
	page, err := u.GetInt("p")
	if err != nil {
		page = 1
	}
	offset, err := u.GetInt("pageoffset")
	if err != nil {
		offset = 15
	}
	id, err := u.GetInt64(":id")
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未选择项目" + err.Error()}
		u.ServeJSON()
		return
	}
	createStarted := u.GetString("createStarted")
	createEnd := u.GetString("createEnd")
	keywords := u.GetString("keywords")
	condArr := make(map[string]interface{})
	condArr["projectid"] = fmt.Sprintf("%d", id)
	condArr["createStartedint"] = createStarted
	condArr["createEndint"] = createEnd
	condArr["keywords"] = keywords

	countTest := PlanPageCountExec(condArr, page, offset)
	paginator := pagination.SetPaginator(u.Ctx, offset, countTest)
	modeData := PlanPageExec(condArr, page, offset)
	type data struct {
		Needs    []ProjectsPlanDto
		Total    int64
		PageNums int
		Page     int
	}
	d := &data{modeData, paginator.Nums(), paginator.PageNums(), paginator.Page()}
	var responseEntity cores.ResponseEntity
	u.Data["json"] = responseEntity.Build(d).Data
	u.Ctx.Output.Status = responseEntity.StatusCode
	u.ServeJSON()
}

type PlanDTO struct {
	Id              int64 `json:"Id,string"`
	Projectid       int64 `json:"Projectid,string"`
	Title           string
	Vesionno        string
	Started         int64
	Ended           int64
	Actualstarttime int64
	Actualendtime   int64
	Content         string
	Parentplanid    int64 `json:"Parentplanid,string"`
	Created         int64
	Createid        int64 `json:"Createid,string"`
	Status          int   `json:"Status,string"`
	Changed         int64
}

// 如果你的 struct 实现了接口 validation.ValidFormer
// 当 StructTag 中的测试都成功时，将会执行 Valid 函数进行自定义验证
func (u *PlanDTO) Valid(v *validation.Validation) {
	v.Required(u.Title, "name").Message("名称不能为空")
	v.Required(u.Projectid, "Projectid").Message("项目不能为空")
}

// @Title Create plan
// @Description create plan
// @Param	body		body 	projects.PlanDTO	true		"body for plan content"
// @Success 200 {string} string
// @Failure 403 body is empty
// @router / [post]
func (u *PlanProjectController) Create() {
	var dto PlanDTO
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &dto)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&dto)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	userid := u.BaseController.UserUserId
	//雪花算法ID生成
	id := utils.SnowFlakeId()
	pro := new(ProjectsPlan)
	utils.SimpleCopyProperties(pro, dto)
	pro.Id = id
	pro.Createid = userid
	err = AddPlan(*pro)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息添加成功", "id": fmt.Sprintf("%d", id)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息添加失败" + err.Error()}
	}
	u.ServeJSON()
}

// @Title Update plan
// @Description  Update plan
// @Param	id		path 	string	true		"plan id"
// @Param	body		body 	projects.PlanDTO	true		"body for plan content"
// @Success 200 {string} 更新成功
// @Failure 403 body is empty
// @router /:id [put]
func (u *PlanProjectController) Update() {
	ids, err := u.GetInt64(":id")
	if err != nil || ids <= 0 {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "你选择更新的计划为空"}
		u.ServeJSON()
		return
	}
	var dto PlanDTO
	err = json.Unmarshal(u.Ctx.Input.RequestBody, &dto)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&dto)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	userss, err1 := GetPlan(ids)
	if err1 != nil || utils.IsEmpty(userss.Id) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "计划不存在"}
		u.ServeJSON()
		return
	}

	pro := new(ProjectsPlan)
	utils.SimpleCopyProperties(pro, dto)
	err = UpdatePlan(ids, *pro)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功", "id": fmt.Sprintf("%d", ids)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败" + err.Error()}
	}
	u.ServeJSON()
}

// @Title Get
// @Description get needs  by id
// @Param	id		path 	string	true		"The key for needs"
// @Success 200 {object} projects.ProjectsPlan
// @Failure 403 :id is empty
// @router /:id [get]
func (u *PlanProjectController) Get() {
	uid := u.GetString(":id")
	if uid != "" {
		var responseEntity cores.ResponseEntity
		int64, err := strconv.ParseInt(uid, 10, 64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
			return
		}
		modeData, err := GetPlan(int64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
		} else {
			u.Data["json"] = responseEntity.Build(modeData).Data
			u.Ctx.Output.Status = responseEntity.StatusCode
		}
	}
	u.ServeJSON()
}

// @Title Update plan status
// @Description  Update plan status
// @Param	id		path 	string	true		"plan id"
// @Param	status	query 	string	true		"状态"
// @Success 200 {string} 更新成功
// @Failure 403 body is empty
// @router /:id/status [put]
func (u *PlanProjectController) UpdateStatus() {
	ids, err := u.GetInt64(":id")
	if err != nil || ids <= 0 {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "你选择更新的计划为空"}
		u.ServeJSON()
		return
	}
	status, err := u.GetInt("status")
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "状态为空"}
		u.ServeJSON()
		return
	}
	exist, err1 := GetPlan(ids)
	if err1 != nil || utils.IsEmpty(exist.Id) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "不存在"}
		u.ServeJSON()
		return
	}
	err = ChangePlanStatus(ids, u.UserUserId, status)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功", "id": fmt.Sprintf("%d", ids)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败" + err.Error()}
	}
	u.ServeJSON()
}
